# %% [markdown]
# # Marking of data lithofacies(对数据岩相进行标记)

# %% [markdown]
# ## Import third-party packages(导入第三方包)

# %%
import os
import pandas as pd
import numpy as np

import math
import random
from pandas import set_option

# %%
# # calculate RMSE
# from sklearn.metrics import mean_squared_error, confusion_matrix
# import matplotlib.colors as colors
# # sklearn.metrics.mean_squared_error(y_true, y_pred, sample_weight=None, multioutput='uniform_average', squared=True)
# # https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html#sklearn.metrics.mean_squared_error

# %%
# print(tf.__version__)

# %% [markdown]
# numpy+mkl 版本为17.2  
# tensorboard，tensorflow 版本为2.1.0  
# pydot版本为1.4.1, graphviz 版本为0.13.2

# %% [markdown]
# ## Import our custom package(导入自己的包)

# %%
# import senutil as sen
# # from rbflayer import RBFLayer, InitCentersRandom
# import senmodels_classification as smsc

# %%
# mpl.rcParams['font.sans-serif'] = ['SimHei']
# plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
# plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
set_option("display.max_rows", 15)
set_option('display.width', 200)
np.set_printoptions(suppress=True, threshold=5000)

# %%
# 使用GPU训练时候，打开下面注释
os.environ['CUDA_VISIBLE_DEVICES']='0'

# %% [markdown]
# ## Preparation work (data processing, result saving location definition)准备工作

# %% [markdown]
# ### Input Curve Dataset Position(输入曲线数据集位置)

# %%
usual_logs_DataPath = 'facies_data/usual_logs/'

# %%
filename_usual_logs = 'GY1_R_0.125m_整段_2350m-2746m_nolabel.csv'

usual_logs_DataPath = os.path.join(usual_logs_DataPath,filename_usual_logs)
print(usual_logs_DataPath)

# %% [markdown]
# ### Location of Petrographic Dataset（岩相数据集所在位置）

# %%
facies_logs_DataPath = 'facies_data/facies_logs/'

# %%
filename_facies_logs =  'GY1-lithofacies-0512.csv'

# %%
facies_logs_DataPath = os.path.join(facies_logs_DataPath,filename_facies_logs)

# %% [markdown]
# ## Petrographic data calibration（岩相数据标定）

# %%
# 高分辨率相对于低分辨率的倍数, default value = 10 (对应于0.1m); 8 (对应于0.125m)
# A sampling rate of 1m
resolution = 10

# %% [markdown]
# ### Read input curves and expert lithofacies classification data（读取输入曲线和专家岩相分类数据）

# %%
input_vector_data = pd.read_csv(usual_logs_DataPath,engine='python',encoding='GBK')
facies_vector = pd.read_csv(facies_logs_DataPath,engine='python',encoding='GBK')

# %%
input_vector_data

# %%
facies_vector

# %%
# 针对输入曲线
depth_cols = 'DEPTH'
# 针对岩相曲线
depth_begin_col = '起始深度'
depth_end_col = '终止深度'
facies_col = '层名'
well_name_col = '井号'

# %%
pd_well_no = np.full(len(input_vector_data),facies_vector[well_name_col][0])
pd_well_no

# %%


# %% [markdown]
# ### Lithofacies classification calibration（岩相类别标定）

# %%
facies_label = np.unique(facies_vector[facies_col])

'''
facies_label = [
    "High organic matter layered shale lithofacies",
    "High organic striated layered shale lithofacies",
    "Medium organic striated layered shale lithofacies",
    "Low organic matter striated layered shale lithofacies",
    "Medium to low organic matter massive dolomite lithofacies",
    "Low organic matter massive shell limestone lithofacies"
    "Low organic matter massive siltstone lithofacies"
]
'''

facies_labels = ['高有机质层状页岩相', '高有机质纹层状页岩相','中有机质纹层状页岩相','低有机质纹层状页岩相',
                '中低有机质块状白云岩相', '低有机质块状介壳灰岩相', '低有机质块状粉砂岩相']


# facies_labels = ['层状粘土质页岩', '纹层状粘土质页岩','层状长英质页岩','纹层状长英质页岩','介壳灰岩']

# %%
depth_min = 2350
depth_max = 2600
math.floor(depth_min),math.ceil(depth_max)

# %%
# for i in range(math.floor(depth_min),math.ceil(depth_max)+1):
#     print(i)
len(facies_labels[0])

# %%
label_max_lenth = 0

# %%
for i in range(len(facies_labels)):
    if label_max_lenth < len(facies_labels[i]):
        label_max_lenth = len(facies_labels[i])

# %%
len(input_vector_data)

# %%
def generate_random_str(randomlength):
    """
    生成一个指定长度的随机字符串
    """
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str
# ————————————————
# 版权声明：本文为CSDN博主「geerniya」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/geerniya/java/article/details/78497765

# %%
fill_label = generate_random_str(label_max_lenth)
fill_label

# %%
facies_list = np.full(len(input_vector_data),"no_label")

# %%
facies_list = np.full(len(input_vector_data),"no_label")

lower_depth_index = 0
# 深度列标尺初始化
# current_depth = input_vector_data[depth_cols][0]
for i in range(len(facies_vector)):
    depth_min = facies_vector[depth_begin_col][i]
    depth_max = facies_vector[depth_end_col][i]
    current_facies_label = facies_vector[facies_col][i]
    current_facies_label = current_facies_label.strip()
    # 获取当前岩相表的岩性id
    current_facies_id = facies_labels.index(current_facies_label)
    # current_well_no = facies_vector[well_name_col][i]
    if(i%10==0):
        print("depth_min,depth_max:",depth_min,depth_max)
        print("No_" + str(i) + "_layers")
    # lower_depth = math.floor(depth_min)
    # upper_depth = math.ceil(depth_max)
    for j in range(0,len(input_vector_data)):
        current_depth = input_vector_data[depth_cols][j]
        if depth_min <= current_depth:
            if current_depth <= depth_max:
                facies_list[j] = current_facies_id 
                # pd_well_no[j]  = current_well_no
                lower_depth_index = j
                # print(str(j) + ":",current_facies_id)
print("Label Work Finished!")

# %%


# %%
wellname_colunm_data = pd.DataFrame(pd_well_no, columns=["Well Name"])

# %%
facies_colunm_data = pd.DataFrame(facies_list, columns=["Facies"])

# %%
facies_colunm_data

# %%
wellname_colunm_data

# %%
pd_data = pd.concat([input_vector_data, wellname_colunm_data,facies_colunm_data],axis=1)        

# %%
pd_data

# %%
data_save = pd_data[pd_data["Facies"] != "no_label"].reset_index(drop=True)

# %%
data_save

# %%
# facies_id_list = np.full(len(data_save),0)

# %%
# for i in range(len(data_save)):
#     current_facies_id = facies_labels.index(data_save["Facies"][i])
#     # print(current_facies_id)

# %%
# facies_id = pd.DataFrame(current_facies_id, columns=["Facies_id"])

# %%
# pd_data = pd.concat([pd_data,facies_id],axis=1)       

# %%


# %% [markdown]
# ## Label File Results Save（标记结果保存）

# %% [markdown]
# ### Result files header information（结果文件文件头信息）

# %%
well_name = filename_facies_logs.split(".csv")[0]
print(well_name)

# %%
# filename_A ： 'HP1_orginLog_6D_4075m-4280m_R_0.125.csv'
well_name

# %%
data_save

# %%
depth_info = data_save[depth_cols]

# %%
depth_info

# %%
begin_depth = depth_info[0]
end_depth = depth_info[len(depth_info)-1]

# %%
print("begin_depth,end_depth:",begin_depth,end_depth)

# %%
# fianl_facies_logs = well_name + '_'+ str(begin_depth) + '-'+ str(end_depth) +'_facies_vectors_' + str(1/resolution)+ '.csv' 
fianl_facies_logs = well_name + '_facies_vectors_' + str(1/resolution)+ '.csv' 

# %%
print(fianl_facies_logs)

# %% [markdown]
# ### Result dataset save location(结果数据集保存位置)

# %%
Using_DataPath = 'facies_data/train/'

# %%
# Using_DataPath = os.path.join(Using_DataPath,fianl_facies_logs)

# %%
resolution_ratio = 1 / resolution
resolution_ratio

# %% [markdown]
# ### The saved result curve(保存的结果曲线)

# %%
data_save

# %%
# 输出txt
# data_save.to_csv(os.path.join(Using_DataPath,fianl_facies_logs),mode='w',float_format='%.4f',sep='\t',index=None,header=True)
data_save.to_csv(os.path.join(Using_DataPath,fianl_facies_logs),mode='w',float_format='%.4f',encoding='GBK',index=None,header=True)
print("Algorithm is Finished!!")

# %%
print(os.path.join(Using_DataPath,fianl_facies_logs))

# %%


# %%



